package com.zhdl.modules.prefiresys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.IdUtil;
import com.project.common.service.impl.BaseServiceImpl;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.zhdl.modules.prefiresys.entity.*;
import com.zhdl.modules.prefiresys.repository.EventRecordsRepository;
import com.zhdl.modules.prefiresys.service.EventRecordsService;
import com.zhdl.modules.prefiresys.web.request.AlarmRecListRequest;
import com.zhdl.modules.prefiresys.web.request.EventAlarmInfoReq;
import com.zhdl.modules.prefiresys.web.request.EventRecordsListRequest;
import com.zhdl.modules.prefiresys.web.response.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class EventRecordsServiceImpl extends BaseServiceImpl<String, EventRecords, EventRecordsRepository> implements EventRecordsService {

    /**
     * 保存事件记录
     */
    @Override
    public EventRecords addEventRecords(EventRecords eventRecords){
        eventRecords.setId(IdUtil.fastSimpleUUID());
        return insert(eventRecords);
    }

    /**
     * 根据设备状态查询
     */
    @Override
    public boolean findByEventStatus(boolean status){
        List<EventRecords> byEventStatus = repository.findByEventStatus(status);
        return byEventStatus.isEmpty();
    }

    /**
     * 更新事件记录
     */
    @Override
    public EventRecords updateEventRecords(EventRecords eventRecords){
        return update(eventRecords, eventRecords.getId());
    }

    @Override
    public EventRecords findByEventId(String id){
        return selectById(id);
    }

    /**
     * 查询某一条记录 根据 设备Id
     */
    @Override
    public List<EventAlarmInfoResp> findAlarmByEventId(EventAlarmInfoReq eventAlarmInfoReq){
        QDefAreaAlarmRec qAlarmRec = QDefAreaAlarmRec.defAreaAlarmRec;
        BooleanBuilder builder = new BooleanBuilder();
        //查找时间范围段内的信息
        builder.and(qAlarmRec.eventId.eq(eventAlarmInfoReq.getEventId()));

        JPAQuery<EventAlarmInfoListQueryResult> query = jpaQueryFactory()
                .select(Projections.constructor(EventAlarmInfoListQueryResult.class
                        ,qAlarmRec.id
                        ,qAlarmRec.nextAlarmStatus.as("alarmStatus")
                        ,qAlarmRec.startTime
                        ,qAlarmRec.endTime
                        ,qAlarmRec.particlePercent
                        ,qAlarmRec.smokePercent
                ))
                .from(qAlarmRec)
                .where(builder);

        List<EventAlarmInfoListQueryResult> fetch = query
                .orderBy(qAlarmRec.startTime.desc())
                .fetch();

        List<EventAlarmInfoResp> responses = new ArrayList<>();

        fetch.forEach(item -> {
            EventAlarmInfoResp recListResp = new EventAlarmInfoResp();
            BeanUtil.copyProperties(item, recListResp, CopyOptions.create().setIgnoreNullValue(true));
            responses.add(recListResp);
        });

        return responses;
    }

    /**
     * 查询所有记录事件
     *
     * @return
     */
    @Override
    public Page<EventRecordsResp> findAllRecord(EventRecordsListRequest request, Pageable pageable) {
        QEventRecords qEventRecords = QEventRecords.eventRecords;
        QDetectorAreaInfo qDetectorAreaInfo = QDetectorAreaInfo.detectorAreaInfo;
        QDetector qDetector = QDetector.detector;

        BooleanBuilder builder = new BooleanBuilder();
        //查找时间范围段内的信息
        builder.and(qEventRecords.startTime.between(request.getStartTime(), request.getEndTime()));

        if (request.getDetectorId().size() > 0) {
            BooleanBuilder builder1 = new BooleanBuilder();
            for (String id : request.getDetectorId())
                builder1.or(qEventRecords.detectorId.eq(id));

            builder.and(builder1);
        }
        if (request.getAreaId().size() > 0) {
            BooleanBuilder builder1 = new BooleanBuilder();
            for (String id : request.getAreaId())
                builder1.or(qEventRecords.areaId.eq(id));

            builder.and(builder1);
        }


//        JPAQuery<EventRecListQueryResult> query = jpaQueryFactory()
//                .select(Projections.constructor(EventRecListQueryResult.class,
//                        qEventRecords.id,
//                        qEventRecords.eventStatus,
//                        qEventRecords.startTime,
//                        qEventRecords.endTime,
//                        qEventRecords.detectorId,
//                        qEventRecords.areaId,
//                        qDetectorAreaInfo.areaName,
//                        qDetector.detectorName
//                ))
//                .from(qEventRecords)
//                .leftJoin(qDetectorAreaInfo).on(qDetectorAreaInfo.id.eq(qEventRecords.areaId))
//                .leftJoin(qDetector).on(qDetector.id.eq(qEventRecords.detectorId))
//                .where(builder);

        // 创建JPA查询
        JPAQuery<EventRecListQueryResult> query = jpaQueryFactory().select(
                        Projections.constructor(EventRecListQueryResult.class,
                                qEventRecords.id,
                                qEventRecords.eventStatus,
                                qEventRecords.startTime,
                                qEventRecords.endTime,
                                qEventRecords.detectorId,
                                qEventRecords.areaId,
                                qDetectorAreaInfo.areaName,
                                qDetector.detectorName
                        ))
                .from(qEventRecords)
                .leftJoin(qDetectorAreaInfo).on(qDetectorAreaInfo.id.eq(qEventRecords.areaId))
                .leftJoin(qDetector).on(qDetector.id.eq(qEventRecords.detectorId))
                .where(builder);

        long total = query.fetchCount();

        List<EventRecListQueryResult> fetch = query
                .orderBy(qEventRecords.startTime.desc())
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .fetch();

//        long total = jpaQueryFactory().select(qAlarmRec.count()).from(qAlarmRec).
//                where(builder).fetchOne();


        List<EventRecordsResp> responses = new ArrayList<>();

        fetch.forEach(item -> {
            EventRecordsResp recListResp = new EventRecordsResp();
            BeanUtil.copyProperties(item, recListResp, CopyOptions.create().setIgnoreNullValue(true));
            responses.add(recListResp);
        });

        return new PageImpl<>(responses, pageable, total);
    }
}
